<?php

namespace App\Http\Controllers;

use App\Models\CzMobileBlank;
use App\Models\Payment;
use Error;
use Illuminate\Http\Request;

class ApiBaseController extends Controller
{
    public $pageSize = 3;

    public $customer_config_map = [
        'sys_type' => '00',
        'customer_type' => '01',
        'role_id' => [100],
        'dept_id' => 200,
    ];

    //
    public function __construct(Request $request)
    {
        $this->pageSize = request('pageSize', 10);
    }
    // 20220527 验证号码是否属于黑名单
    public function validateMobileIsBlank($mobile)
    {
        return  CzMobileBlank::where('mobile', $mobile)->exists();
    }

    protected function getPayParamsV2($order, $user, $payInfo, $appid)
    {
        $pay_id = $payInfo->id;

        $channel_info = Payment::find($pay_id);
        $setting_arr = $channel_info->setting;
        $setting = [];
        // logger(json_encode($setting_arr));
        // [{"name":"appid","label":"appid","placeholder":"\u8bf7\u8f93\u5165appid(\u652f\u4ed8\u5e73\u53f0\u7684appid)","val":"00299488"},{"name":"cusid","label":"\u5546\u6237\u53f7","placeholder":"\u8bf7\u8f93\u5165\u5546\u6237\u53f7(\u652f\u4ed8\u5e73\u53f0\u7684\u5546\u6237\u53f7)","val":"660588048161YJT"},{"name":"privateKey","label":"\u79c1\u94a5","placeholder":"\u8bf7\u8f93\u5165\u79c1\u94a5","val":"MIIEpAIBAAKCAQEAsAO8QahoWXaVv1r6wxbB94GIzB2klnFsm3JTv3LRGffRaHYRYSLCRuA52Xo6aKZvKWBra+HB0xftAXm0CjaMS13IiRfzefnC+5AXXCwlE2hCMO\/5g3itk6xNjxzUsNuNhA7puOzn+xboam5uFtSiBdqwZhBftn1X8lqp4Gnf7CVBA80CTWgniCSxqDgZY47\/Y1ejMw0\/wmof5J8yQVBafuBmvwm+WMz9rOkxLqoB7TkEuK5DDXQ3Qan2GG1CQRe1Qi3mfOSTFTDQQaCWHHr+hQQTFVPENVmbX9bxPb1K+OCpWU9gmgnpPI29pDgd1ms37WdfQM2J0sdXvllMeqIfTwIDAQABAoIBAAK3zAxngVUAU8ekrAKfM1eTFH2yZ3w7PCYaWdi2+Suh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IB2YqD\/xxGukUpn9taqB35ag3pemJJl2AF6m8B\/dazwzEqzc2MpCMmuSFZQ\/Iythio6SAAZM1JwdGKJWhDeCIWTPYMk9acgq+w=="},{"name":"privateKey","label":"\u516c\u94a5","placeholder":"\u8bf7\u8f93\u5165\u516c\u94a5","val":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm9OV6zH5DYH\/ZnAVYHscEELdCNfNTHGuBv1nYYEY9FrOzE0\/4kLl9f7Y9dkWHlc2ocDwbrFSm0Vqz0q2rJPxXUYBCQl5yW3jzuKSXif7q1yOwkFVtJXvuhf5WRy+1X5FOFoMvS7538No0RpnLzmNi3ktmiqmhpcY\/1pmt20FHQQIDAQAB"},{"name":"sign_type","label":"\u7b7e\u540d\u65b9\u5f0f","placeholder":null,"val":"RSA"}]  
        foreach ($setting_arr as $key => $v) {
            $setting[$v['name']] = $v['val'];
        }
        // logger(json_encode($setting));
        // logger($setting['privateKey']);
        $setting['channel_code'] = $channel_info->payment_code;
        $setting['channel_id'] = $pay_id;
        $setting['callback_url'] = $channel_info->callback_url;
        $temp_file = $channel_info->file_path ?? $channel_info->channel_code;
        $channel_file = base_path("payChannel/" . $temp_file . ".php");
        logger('order_sn:' . $order->order_sn . ',channel_file:' . $channel_file);
        include_once $channel_file;
        logger('order_sn:' . $order->order_sn . 'setting:' . json_encode($setting));
        $obj = new $channel_info['payment_code']($setting);

        $submitData = [
            'OutTradeNo' => $order->order_sn,
            'Body' => $order->product_name ?? '充值支付',
            'TotalAmount' => $order->price * 100,
            'OpenId' => $order->openid,
            'SubAppId' => $appid,
            "success_back_page" => ""
        ];

        $res = $obj->submitOrder($submitData);
        $data = [
            "code" => 200,
            "msg" => "",
            "payInfo" => []
        ];
        if ($res['status'] == 1) {
            $data['payInfo'] = $res['payInfo'];
            $data['msg'] = "获取成功";
        } else {
            $data['code'] = 500;
            $data['msg'] = $res['msg'] ?? '支付参数获取失败';
        }
        return $data;
    }



    public function httpRequest($url, $method, $postfields = null, $cookie = '', $refer = '', $headers = array(), $debug = false)
    {
        //header("Content-type:text/html;charset=utf-8");
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 0); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 120); /* 设置cURL允许执行的最长秒数*/
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_COOKIE, $cookie);/* * *COOKIE带过去** */
        //伪造来源referer
        //        curl_setopt ($ci,CURLOPT_REFERER,'http://sb777.cn:8080/tohersystem/rechargeOrder.do?action=distribution&isDistribution=true');
        curl_setopt($ci, CURLOPT_REFERER, $refer);

        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if (!$response) {
            // 请求异常才记录
            $log_file_name = __DIR__ . '/../../../storage/logs/' . date("Y-m-d") . 'request.txt';
            file_put_contents($log_file_name, "--------请求信息：---------", FILE_APPEND);
            file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            file_put_contents($log_file_name, json_encode($requestinfo) . "\r\n", FILE_APPEND);
            file_put_contents($log_file_name, '状态码:' . $http_code, FILE_APPEND);
            file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            if ($method == 'POST') {
                file_put_contents($log_file_name, "--------请求参数：---------", FILE_APPEND);
                file_put_contents($log_file_name, "\r\n", FILE_APPEND);
                file_put_contents($log_file_name, $tmpdatastr . "\r\n", FILE_APPEND);
                file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            }
        }
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
}
